package com.duqc.tag.service.impl.strategy;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName TagStrategyFactory
 * @Description TagStrategyFactory
 * @Author duqc
 * @Date 2023/2/9
 **/
@Component
public class TagStrategyFactory implements ApplicationContextAware {

    private static Map<String, TagDataStrategy> map;

    static volatile TagStrategyFactory tagStrategyFactory;

    private TagStrategyFactory() {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(TagStrategy.class);
        List<TagDataStrategy> strategies = new ArrayList<>();
        beans.forEach((key, value) -> {
            Object bean = applicationContext.getBean(key);
            strategies.add((TagDataStrategy) bean);
        });
        setMap(strategies);
    }

    /**
     * 设置map信息
     * 非静态方法避免访问静态变量
     *
     * @param strategies list
     */
    private static void setMap(List<TagDataStrategy> strategies) {
        map = strategies.stream().filter(info -> StringUtils.isNotBlank(info.getType()))
                .collect(Collectors.toMap(TagDataStrategy::getType, strategy -> strategy));
    }

    public TagDataStrategy get(String type) {
        return map.get(type);
    }

    /**
     * 获取对象实例
     *
     * @return StrategyFactory
     */
    public static TagStrategyFactory getInstance() {
        if (tagStrategyFactory == null) {
            synchronized (TagStrategyFactory.class) {
                if (tagStrategyFactory == null) {
                    tagStrategyFactory = new TagStrategyFactory();
                }
            }
        }
        return tagStrategyFactory;
    }

}
